package cn.tedu.charging.order.rabbit;

import cn.tedu.charging.order.config.RabbitConfiguration;
import cn.tedu.charging.order.pojo.po.OrderMQPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//静态导入
import static cn.tedu.charging.order.config.RabbitConfiguration.ROUTING_KEY;

@Slf4j
@Component
public class RabbitMQOrderProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    public void sendOrder(OrderMQPO orderMQPO){
        //设置RabbitMQ return的回调类 并回执
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            //returnedMessage 包含被退掉的消息，消息本身，错误码，错误信息,
            //退订发生哪个交换机，发生在哪个路由key
            log.debug("returnMessage:{}",returnedMessage);
        });

        //设置RabbitMQ的确认confirm 机制的回调类 保证生成者消息不丢
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            log.debug("RabbitMQ确认回调:correlationData={},ack={},cause={}",correlationData,ack,cause);
            if(ack){
                log.debug("RabbitMQ成功收到了消息");
            }else {
                log.debug("RabbitMQ没有收到了消息，打日志，进行重试，重新发送");
            }
        });

        rabbitTemplate.convertAndSend(RabbitConfiguration.EXCHANGE_NAME,
                RabbitConfiguration.ROUTING_KEY,orderMQPO);
    }
}
